package com.cch.filter;

import com.cch.security.PhoneNumAuthenticationToken;
import com.cch.service.UserDetailService;
import com.cch.util.SecurityUtils;
import com.cch.util.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * token过滤器 验证token有效性
 *
 * @author ruoyi
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private UserDetailService userDetailService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {


        String token = request.getHeader("Authorization");
        System.out.println("----》     JwtAuthenticationTokenFilter，验证token过滤器，获取到的token值："+token);

        //为空时候继续下一步过滤链，即进行登录认证。后续进行格式验证，如果以bearer开始去掉前面的前缀
        if (!StringUtils.hasText(token) ) {
            System.out.println("----》     JwtAuthenticationTokenFilter，token验证："+"token为空！");
            chain.doFilter(request, response);
            return;
        }
        if (token.startsWith("Bearer ")) {
            System.out.println("----》     JwtAuthenticationTokenFilter，token格式验证中："+"token格式以Bearer开头，去掉开头！");
            token = token.substring(7);
        }

        //验证token是否过期
        boolean isValid = TokenUtil.validateJwtToken(token);//只在util中只验证是否过期了。
        if (!isValid) {
            System.out.println("----》     token验证失败，token过期。");
            return;
        }
        //获取token载荷中的用户信息
        Claims claims = tokenUtil.parseClaim(token).getPayload();
        String userid = claims.get("username").toString();
        //此处也可以通过redis  缓存获取用户信息
        UserDetails userDetails = userDetailService.loadUserByUsername(userid);
        if (userDetails != null && SecurityUtils.getAuthentication() == null) {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        chain.doFilter(request, response);
    }
}
